package com.guojian.common.format;

import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import org.apache.commons.lang.StringUtils;
import com.guojian.common.utils.StringUtilss;

public class MyDecimalFormat extends Format {

	private static final long serialVersionUID = 1L;

	private Format defaultFormat = new DecimalFormat("#.##%");

	private static MyDecimalFormat GOODSIDFORMAT = new MyDecimalFormat("000000");// 商品编码6位

	public MyDecimalFormat() {
	}

	public MyDecimalFormat(String pattern) {
		this.defaultFormat = new DecimalFormat(pattern);
	}

	@Override
	public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
		if (obj == null) {
			obj = StringUtils.EMPTY;
		}
		if (StringUtilss.isNumber(obj)) {
			obj = defaultFormat.format(Double.parseDouble(obj.toString()));
		}
		return toAppendTo.append(obj);
	}

	@Override
	public Object parseObject(String source, ParsePosition pos) {
		if (StringUtils.isBlank(source)) {
			return 0;
		}
		try {
			return defaultFormat.parseObject(source, pos);
		} catch (Exception e) {
			return 0;
		}
	}

	public double parseDoubleObject(String source) {
		try {
			return StringUtilss.getDoubleObject(defaultFormat.parseObject(source));
		} catch (ParseException e) {
			return 0d;
		}
	}

	public static MyDecimalFormat getGoodsIDFormat() {
		return GOODSIDFORMAT;
	}

	public static void main(String[] args) {
		MyDecimalFormat format = new MyDecimalFormat();
		System.out.println(format.parseDoubleObject("-4.3411%"));
	}
}
